<?php

namespace App\Models\Traits;
use Cache;
trait HotTagsHelper
{
    protected $cache_key = 'hot_tags_';
    protected $tags = [];
    protected $categories = [1,2,3];
    protected $cache_expire_in_minutes = 180;

    public function getHotTags($category_id = 1)
    {
        // 尝试从缓存中取出 cache_key 对应的数据。如果能取到，便直接返回数据。
        // 否则运行匿名函数中的代码来取出活跃用户数据，返回的同时做了缓存。
        return Cache::remember($this->cache_key . $category_id, $this->cache_expire_in_minutes, function() use ($category_id){
             $data = $this->calculateHotTags();
             return $this->tag_idToArray($data[$category_id]);
        });
    }


    public function calculateHotTags()
    {
      if (! $tags = $this->tags) {
        $tags = $this->pluck('id');
      }
      $tags = collect($tags)->flip();
      $categories = \App\Models\Category::pluck('id');
      $data = [];
      $tagModel = $this;
      foreach ($categories as $category) {
        $data[$category] = collect($tags)->map(function ($tag, $index) use ($tagModel, $category){
          $tag_info = $tagModel->where('id', $index)->withCount(['pictuers' => function($query) use ($category){
            $query->where('category_id', $category);
          }])->first();
          return $tag_info->pictuers_count;
        });
        $data[$category] = collect($data[$category])->sortByDesc(function ($item, $index) {
          return $item;
        })->forPage(1,15)->keys();
      }
      $this->cacheHotTags($data);
      return $data;
    }
    private function tag_idToArray($tags_ids)
    {
      return $tags_data = $this->whereIn('id', $tags_ids)->get()->toArray();
    }
    private function cacheHotTags($hot_tags)
    {
        // 将数据放入缓存中
        foreach($this->categories as $category) {
          $tags_ids = $hot_tags[$category];
          $tags_data = $this->tag_idToArray($tags_ids);
          Cache::put($this->cache_key . $category, $tags_data, $this->cache_expire_in_minutes);
        }
    }
}
